// pages/gps/studentgps.js
var db = wx.cloud.database()
var QQMapWX = require('../../libs/qqmap-wx-jssdk');
var qqmapsdk;
const util = require('util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name:"",
    _id:"",
    teachermeter:"",
    cantime:"",
    teacherlocation:"",
    nowtime:"",
    studentlocation:"",
    nowplace:"",
    jlmeter:"",
    differtime:"",
    checkif:true,
    checkinfo:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  
  gpsqx:function(){
    wx.authorize({
      scope: 'scope.userLocation',//发起定位授权
      success: function () {
        console.log('有定位授权')
      //授权成功，此处调用获取定位函数
      }, fail() {
     //如果用户拒绝授权，则要告诉用户不授权就不能使用，引导用户前往设置页面。
        console.log('没有定位授权')
        wx.showModal({
          cancelColor: 'cancelColor',
          title: '没有授权无法获取位置信息',
          content: '是否前往设置页面手动开启',
          success: function (res) {
            if (res.confirm) {
              wx.openSetting({
                withSubscriptions: true,
              })
            } else {
              wx.showToast({
                icon: 'none',
                title: '您取消了定位授权',
              })
            }
          }, fail: function (e) {
            console.log(e)
          }
        })
      }
    })
    
      this.gpsdw();
   
     
  },
  gpsdw:function(){
    var _that=this;
    wx.getLocation({
      type: 'gcj02',
     }).then(res=>{
      const latitude = res.latitude
      const longitude = res.longitude
      const speed = res.speed
      const accuracy = res.accuracy
      console.log("gps",res.latitude,res.longitude)
      _that.setData({
        studentlocation:{
          longitude:longitude,
          latitude:latitude
        }
      })
      //经纬度计算老师距离学生距离
      console.log("teacherlocation",_that.data)
      var mete = _that.distance(_that.data.teacherlocation.latitude,_that.data.teacherlocation.longitude,
        _that.data.studentlocation.latitude,_that.data.studentlocation.longitude);
      console.log("mete",mete)
      _that.setData({
         jlmeter:mete*1000
      })
      var time = new Date(_that.data.cantime)
      var time0 = new Date(_that.data.nowtime)
      time.setTime(time-time0)
      console.log("相差的时间",time.getTime());
      qqmapsdk.reverseGeocoder({
        location:{
          latitude:latitude,
          longitude:longitude
        },
        success: function(res) {//成功后的回调
          console.log(res.result.address);
          _that.setData({
            nowplace:res.result.address,
            differtime:time.getTime()
          })
        }
      })
     })
     
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var o = wx.getStorageSync("name");
    console.log("学生姓名为:",o)
    this.setData({
      name:o
    })
    qqmapsdk = new QQMapWX({
      key: 'QD5BZ-53ZRF-4MHJF-JD6NW-Y4K3F-PPFOH'
    });
    console.log(options.number)
    db.collection("class").where({
      number:options.number
    }).get().then(res=>{
      console.log("查询班级情况,有效时间距离等",res.data[0])
      if(res.data[0].yqdname.lenght!=0){
        res.data[0].yqdname.forEach(item => {
          if(item == o){
            this.setData({
              checkinfo:true
            })
          }
        });
        if(this.data.checkif == true){console.log("该同学已签到")}
      }
      
      this.setData({
        _id:res.data[0]._id,
        teachermeter:res.data[0].canmeter,
        cantime:res.data[0].cantime,
        teacherlocation:res.data[0].location,
        checkif:res.data[0].checkif
      })
    var user = wx.getStorageSync("user");
     console.log("user",user)

    //获取data格式的时间
    const util = require('util.js');
    var myDate = new Date();
    myDate = util.formatDate(myDate, 'yyyy-mm-dd hh:mi:ss');
    console.log("当前时间为:",myDate);

    
    this.setData({
      nowtime:myDate
    })
    this.gpsqx()
    })

  
    
  },
  qiandao:function(){
    wx.showLoading({
      title: '正在签到中',
      mask:true
    })
    if(this.data.checkinfo == false){
    if(this.data.checkif == true){
        if(this.data.differtime > 0 ){
          if(this.data.jlmeter < this.data.teachermeter){
            
           
            wx.cloud.callFunction({
              name:"update",
              data:{
                table:"class",
                docid:this.data._id,
                shux:"checkstudent",
                classname:this.data.name
                } 
            }).then(res=>{
              this.setData({
                checkinfo:true
              })
              wx.hideLoading({
              })
              
            })


          }else{
            console.log("相差距离太远,您距离老师仍有",this.data.jlmeter,"米")
            wx.hideLoading({
            })
            wx.showToast({
              title: '您距离老师太远了呢',
              icon: 'none',    //如果要纯文本，不要icon，将值设为'none'
              duration: 1800 
            })  
          }
        
      }else{
        console.log("签到已过期分钟数:",this.data.differtime/60/1000)
        wx.hideLoading({
        })
        wx.showToast({
          title: '签到时间已过',
          icon: 'none',    //如果要纯文本，不要icon，将值设为'none'
          duration: 1800 
        })  
      }
    }else{
      wx.hideLoading({
      })
      wx.showToast({
        title: '老师已暂停签到',
        icon: 'none',    //如果要纯文本，不要icon，将值设为'none'
        duration: 1800 
      })  
    }}else{
      wx.hideLoading({
      })
      wx.showToast({
        title: '您已签到成功',
        icon: 'none',    //如果要纯文本，不要icon，将值设为'none'
        duration: 1800 
      }) 
    }
    
  },
  distance: function (la1,lo1,la2,lo2) {
      // console.log("la1",la1)
      // console.log("lo1",lo1)
      // console.log("la2",la2)
      // console.log("lo2",lo2)
      var La1 = la1 * Math.PI / 180.0;
      var La2 = la2 * Math.PI / 180.0;
      var La3 = La1 - La2;
      var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
      // console.log("La1",La1,"La2",La2,"La3",La3,"Lb3",Lb3)
      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
      s = s * 6378.137;
      s = Math.round(s * 10000) / 10000;
      s = s.toFixed(2);
      return s;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})